package com.jajahome.feature.user.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.jajahome.R;
import com.jajahome.alipay.PayResult;
import com.jajahome.base.BaseFragment;
import com.jajahome.constant.Constant;
import com.jajahome.event.EventMessage;
import com.jajahome.feature.user.adapter.DesignApplySelectPhotoAdapter;
import com.jajahome.feature.user.adapter.UserItemAdapter;
import com.jajahome.feature.view.LoginDialog;
import com.jajahome.model.AlipayModel;
import com.jajahome.model.AuditModel;
import com.jajahome.model.AvatarModel;
import com.jajahome.model.JWeichatPayModel;
import com.jajahome.model.LoginModle;
import com.jajahome.model.PayPriceModel;
import com.jajahome.model.SimpleModel;
import com.jajahome.model.TimeModel;
import com.jajahome.model.UserActionModel;
import com.jajahome.model.UserMessageModel;
import com.jajahome.network.ApiImp;
import com.jajahome.network.BaseReq;
import com.jajahome.network.DesignerReq;
import com.jajahome.network.HttpCode;
import com.jajahome.network.HttpUtil;
import com.jajahome.network.ReqPage;
import com.jajahome.pop.PopPay;
import com.jajahome.pop.PopShare;
import com.jajahome.util.Base64Helper;
import com.jajahome.util.GlideEngine;
import com.jajahome.util.LoginUtil;
import com.jajahome.util.SPUtils;
import com.jajahome.util.StringUtil;
import com.jajahome.util.T;
import com.jajahome.util.TimeUtil;
import com.jajahome.util.convertutils.ErrorUtil;
import com.jajahome.widget.SharedPreferencesUtils;
import com.jajahome.widget.recyclerview.MultiRecycleView;
import com.jajahome.wxapi.WXPayEntryActivity;
import com.jajahome.wxapi.WxPayApi;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.squareup.picasso.Picasso;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yalantis.ucrop.UCrop;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.app.Activity.RESULT_OK;

/**
 * Created by tuxuesong on 2018/4/26.
 */
public class UserActForFragment extends BaseFragment implements View.OnClickListener, UserItemAdapter.ActionListener {

    public static final int CHANGE_ACTION = 0X46;
    public static final int MPAY_METHOD = 0x33;
    private static final int SUPER_DESIGNER_APLIAY = 0x06;

    @BindView(R.id.recyclerView)
    MultiRecycleView recycleView;

    @BindView(R.id.image_person)
    CircleImageView imagePerson;
    @BindView(R.id.tv_apply)
    TextView tvApply;
    @BindView(R.id.tv_new_x)
    TextView tvNewX;
    @BindView(R.id.img_v)
    ImageView imgV;
    @BindView(R.id.time_desc)
    TextView timeDesc;
    @BindView(R.id.tv_name)
    TextView user_name;
    @BindView(R.id.pay_super_designer)
    TextView pay_super_designer;//申请超级vip
    @BindView(R.id.tv_vip)
    TextView tv_vip;//申请vip
    @BindView(R.id.pay_vip)
    TextView pay_vip;//续费Vip
    @BindView(R.id.tv_control_price)
    TextView tvControlPrice;//续费Vip

    @BindView(R.id.ibtn_back)
    ImageButton iBtnBack;//续费Vip

    @BindView(R.id.ibtn_news)
    FrameLayout ibtnNews;

    private GradientDrawable p;
    private int payVIP = 0;//0不重要，1为vip用户续费用

    private PopShare mPopShare;
    private PopPay mPopPay;
    private String path;
    private String str;
    private LoginModle info = null;
    private IWXAPI mIwxapi;
    private IWeiboShareAPI mIWeiboShareAPI;      //微博api
    private UserItemAdapter adapter;
    private boolean isClick = false;
    public static final String Tag = "UserAct01";
    private static final int SDK_PAY_FLAG = 1;
    private List<UserActionModel> actionList = new ArrayList<>();


    @Override
    protected int getViewId() {
        return R.layout.act_user01;
    }

    @Override
    protected void init() {
        initViewController(recycleView);
        recycleView.setRefreshEnable(false);
        recycleView.setLoadMoreable(false);
        adapter = new UserItemAdapter();
        recycleView.setAdapter(adapter);
        recycleView.setGridLayout(4);
        mIwxapi = WXAPIFactory.createWXAPI(mContext, Constant.WEICHAT_APP_ID, true);
        //新浪微博分享
        mIWeiboShareAPI = WeiboShareSDK.createWeiboAPI(getActivity(), Constant.WEIBO_APP_KEY);
        mIWeiboShareAPI.registerApp();    // 将应用注册到微博客户端
        imagePerson.setOnClickListener(this);
//        tvApplyName.setOnClickListener(this);
        tvApply.setOnClickListener(this);
        tv_vip.setOnClickListener(this);
        pay_vip.setOnClickListener(this);
        pay_super_designer.setOnClickListener(this);
        adapter.setListener(this);
        p = (GradientDrawable) tvApply.getBackground();
        initList();
        iBtnBack.setVisibility(View.INVISIBLE);
        ibtnNews.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), NewsAct.class));
            }
        });
    }

    private void initList() {
        actionList.add(new UserActionModel(R.mipmap.ic_all_order_02, "全部订单", ""));
        actionList.add(new UserActionModel(R.mipmap.ic_all_collected, "收藏", ""));
        actionList.add(new UserActionModel(R.mipmap.ic_coupon, "优惠券", ""));
        actionList.add(new UserActionModel(R.mipmap.ic_vip_center, "会员中心", ""));
        actionList.add(new UserActionModel(R.mipmap.ic_share_invite, "分享邀请", ""));
        actionList.add(new UserActionModel(R.mipmap.ic_all_friends, "好友", ""));
        actionList.add(new UserActionModel(R.mipmap.ic_all_reward, "奖励", ""));
        actionList.add(new UserActionModel(R.mipmap.ic_gold, "金币", ""));
        actionList.add(new UserActionModel(R.mipmap.ic_foot_log, "足迹", ""));
      //  actionList.add(new UserActionModel(R.mipmap.ic_crowd_funding, "众筹", ""));
        actionList.add(new UserActionModel(R.mipmap.ic_find_home, "找我家", ""));
        actionList.add(new UserActionModel(R.mipmap.ic_sign_c, "签到", ""));
        actionList.add(new UserActionModel(R.mipmap.ic_all_adress, "地址", ""));
        actionList.add(new UserActionModel(R.mipmap.ic_c_ser, "客服", ""));
        //actionList.add(new UserActionModel(R.mipmap.ic_help, "帮助", ""));
        actionList.add(new UserActionModel(R.mipmap.ic_settting, "设置", ""));
        adapter.addItems(actionList);
    }

    @Override
    public void onResume() {
        super.onResume();
        getUserInfo();
        //  setData();
        getUserMessage();
        new Thread(setDataThread).start();
    }

    /**
     * 连接服务器，获取用户信息
     */
    private void getUserInfo() {
        if (LoginUtil.getInfo(mContext) == null) return;
        BaseReq baseReq = new BaseReq();
        baseReq.setCmd(Constant.USERINFO);
        BaseReq.ContentBean contentBean = new BaseReq.ContentBean();
        baseReq.setContent(contentBean);
        Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(baseReq));
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/session"), gson.toJson(LoginUtil.getInfo(mContext).getData().getSession()));
        mSubscription = ApiImp.get().userInfo(requestBody, requestBody1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SimpleModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ErrorUtil.showMessage(mContext, e);
                        startActivity(LoginAct.class);

//                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(SimpleModel model) {
                        if (model.getStatus() == HttpCode.INVALID_LOGIN_STATE) {
                            /*showLoginStatusErrorDialog(0);*/
                        } else if (model.getStatus() != HttpCode.SUCCESS) {
                            showToast(model.getMessage());
                        } else if (model.getStatus() == HttpCode.SUCCESS) {
                            Gson gson = new Gson();
                            LoginModle loginModle = gson.fromJson(gson.toJson(model), LoginModle.class);
                            info = LoginUtil.getInfo(mContext);
                            info.getData().setUser(loginModle.getData().getUser());
                            LoginUtil.saveInfo(mContext, info);
                            setData();
                        }
                    }
                });

    }

    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            if (what == 0) {
                //在主线程中需要执行的操作，一般是UI操作
                setData();
            }
        }
    };

    //防止数据不能加载
    Runnable setDataThread = new Runnable() {
        @Override
        public void run() {
            //在子线程中执行任务，执行完成或需要通知UI线程时调用以下方法
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mhandler.sendEmptyMessage(0);
        }
    };

    private void setData() {
        if (info != null && info.getData() != null) {
            LoginModle.DataBean.UserBean userBean = info.getData().getUser();
            if (userBean == null) return;
            String inviteCode = userBean.getInvitecode();
            int count = recycleView.getRecyclerView().getChildCount();
            user_name.setText(userBean.getNickname());
            Log.i("printRecy", "count" + count);
            for (int i = 0; i < count; i++) {
                switch (i) {
                    case 4:
                    case 5:
                    case 6:
                    case 7:
                        View child = recycleView.getRecyclerView().getChildAt(i);
                        LinearLayout ll = (LinearLayout) child;
                        TextView friendTv = (TextView) ll.getChildAt(2);
                        if (i == 4) {
                            if (StringUtil.isEmpty(inviteCode)) {
                                friendTv.setText("");
                            }
                            friendTv.setText(inviteCode);
                        }
                        if (i == 5) {
                            friendTv.setText(userBean.getFriends() + "");
                        }
                        if (i == 6) {
                            friendTv.setText(userBean.getAssets() + "");
                        }
                        if (i == 7) {
                            friendTv.setText(userBean.getIntegral() + "");
                        }
                        break;
                }
            }
            setType(userBean);
            LoginModle.DataBean.UserBean.AvatarBean avatarBean = info.getData().getUser().getAvatar();
            if (avatarBean != null) {
                String avatarUrlBig = avatarBean.getSmall();
                if (!StringUtil.isEmpty(avatarUrlBig)) {
                    Picasso.with(getActivity()).load(info.getData().getUser().getAvatar().getUrl()).error(R.mipmap.ic_holder_header_big).placeholder(R.mipmap.ic_holder_header_big).into(imagePerson);
                } else {
                    imagePerson.setImageResource(R.mipmap.ic_holder_header_big);
                }
            } else {
                imagePerson.setImageResource(R.mipmap.ic_holder_header_big);
            }
        }
    }

    private void viewGone() {
        pay_super_designer.setVisibility(View.GONE);
        timeDesc.setVisibility(View.GONE);
        tv_vip.setVisibility(View.GONE);
        pay_vip.setVisibility(View.GONE);
    }

    private void setType(LoginModle.DataBean.UserBean userBean) {
        if (userBean == null || StringUtil.isEmpty(userBean.getType())) return;
        //0 游客 ,1 注册用户(一般用户), 2 设计师(申请中), 3 认证设计师(审核通过), 4装饰公司,5 城市合伙人,6协会 7 服务商,8 内部员工
        tvApply.setVisibility(View.VISIBLE);
        switch (userBean.getType()) {
            case "1":
                isClick = true;
                //   tvApply.setText(R.string.apply_designer);
                //   tvApply.setVisibility(View.GONE);
                //   superDesigner.setVisibility(View.GONE);
                //   beSuperDesigner.setVisibility(View.GONE);
                tvApply.setVisibility(View.VISIBLE);
                tvApply.setText(R.string.apply_designer);
                imgV.setVisibility(View.INVISIBLE);
                tvApply.setTextColor(Color.WHITE);
                p.setColor(mContext.getResources().getColor(R.color.golden));
                viewGone();
                break;
            case "2":
                //                tvApplyName.setVisibility(View.GONE);
                //                superDesigner.setVisibility(View.GONE);
                //                beSuperDesigner.setVisibility(View.GONE);
                isClick = false;
                p.setColor(mContext.getResources().getColor(R.color.golden));
                tvApply.setVisibility(View.VISIBLE);
                tvApply.setText(R.string.applying_designer);
                imgV.setVisibility(View.INVISIBLE);
                tv_vip.setVisibility(View.VISIBLE);//申请vip
                pay_super_designer.setVisibility(View.GONE);
                timeDesc.setVisibility(View.GONE);
                pay_vip.setVisibility(View.GONE);
                break;
            case "3":
//                tvApplyName.setVisibility(View.GONE);
//                superDesigner.setVisibility(View.GONE);
                tv_vip.setVisibility(View.GONE);
                pay_vip.setVisibility(View.GONE);
                isClick = false;
                p.setColor(mContext.getResources().getColor(R.color.golden));
                controlVIPPrice(userBean.getId());
                if (info != null) {
                    int type_class = info.getData().getUser().getType_class();
                    if (type_class == 1) {//认证vip，下方显示时间，右边显示申请超级vip
                        tvApply.setText(R.string.designer);
                        imgV.setImageResource(R.mipmap.ic_v_designer);
                        imgV.setVisibility(View.VISIBLE);
                        pay_super_designer.setVisibility(View.VISIBLE);//申请超级vip
                        getUserTime();
                    } else if (type_class == 5) {
                        // tvApply.setText(R.string.super_designer);
                        // superDesigner.setVisibility(View.GONE);
                        // beSuperDesigner.setVisibility(View.VISIBLE);
                        tvApply.setText(R.string.super_vip);
                        imgV.setImageResource(R.mipmap.ic_v_super_designer);
                        imgV.setVisibility(View.VISIBLE);
                        pay_super_designer.setVisibility(View.GONE);
                        getUserTime();
                    } else {
                        tvApply.setText(R.string.designer);
                        imgV.setImageResource(R.mipmap.ic_v_designer);
                        imgV.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case "4":
                isClick = false;
                tvApply.setText(R.string.decoration_company);
                p.setColor(mContext.getResources().getColor(R.color.golden));
                imgV.setImageResource(R.mipmap.ic_v_decoration_company);
                imgV.setVisibility(View.VISIBLE);
//                superDesigner.setVisibility(View.GONE);
                break;
            case "5":
                p.setColor(mContext.getResources().getColor(R.color.golden));
                isClick = false;
                tvApply.setText(R.string.city_partner);
                imgV.setImageResource(R.mipmap.ic_v_city_partner);
                imgV.setVisibility(View.VISIBLE);
//                superDesigner.setVisibility(View.GONE);
                break;
            case "6":
                isClick = false;
                p.setColor(mContext.getResources().getColor(R.color.golden));
                tvApply.setText(R.string.xiehui);
                imgV.setImageResource(R.mipmap.ic_v_xiehui);
                imgV.setVisibility(View.VISIBLE);
//                superDesigner.setVisibility(View.GONE);
                break;
            case "7":
                isClick = false;
                p.setColor(mContext.getResources().getColor(R.color.golden));
                tvApply.setText(R.string.facilitator);
                imgV.setImageResource(R.mipmap.ic_v_facilitator);
                imgV.setVisibility(View.VISIBLE);
//                superDesigner.setVisibility(View.GONE);
                break;
            case "8":
                isClick = false;
                p.setColor(mContext.getResources().getColor(R.color.golden));
                tvApply.setText(R.string.internastaff);
                imgV.setImageResource(R.mipmap.ic_v_internastaff);
                imgV.setVisibility(View.VISIBLE);
//                superDesigner.setVisibility(View.GONE);
                break;
            default:
                p.setColor(mContext.getResources().getColor(R.color.golden));
                break;
        }
    }


    /**
     * 获取用户消息
     */
    private void getUserMessage() {
        ReqPage.ContentBean.PaginationBean paginationBean = new ReqPage.ContentBean.PaginationBean();
        paginationBean.setOffset(1);
        paginationBean.setLimit(Constant.PAGE_LIMIT);
        ReqPage reqPage = new ReqPage();
        reqPage.setCmd(Constant.USER_MESSAGE);
        Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(reqPage));
        mSubscription = ApiImp.get().getUserMessage(requestBody, HttpUtil.getSession(mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserMessageModel>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(UserMessageModel userMessageModel) {
                        if (userMessageModel.getStatus() == HttpCode.SUCCESS) {
                            String newNums = userMessageModel.getData().getNewX();
                            if (StringUtil.isEmpty(newNums) || "0".equals(newNums)) {
                                tvNewX.setVisibility(View.GONE);
                            } else {
                                tvNewX.setText(newNums);
                                tvNewX.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_person:
                /**
                 * 选择图片
                 */
                checkPermission();
                break;
            case R.id.tv_apply:
                /**
                 * 跳转到申请设计师列表
                 */
                if (isClick)
                    if (!setPhone()) {
                        LoginDialog.Builder builder = new LoginDialog.Builder(mContext);
                        builder.setMessage("您还未绑定手机号\n是否绑定?");
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                return;
                            }
                        });
                        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                startActivity(PhoneAct.class);
                            }
                        });
                        builder.create().show();
                    } else {
                        getDesignerAuditFlag();
                    }
                break;
            case R.id.tv_vip://申请中状态，升级认证vip或者超级vip
                payVIP = 0;
                payPrice();
                break;
            case R.id.pay_super_designer://已经是vip用户，升级超级vip用户
                mPopPay = null;
                payVIP = 0;
                payPrice();
                break;
            case R.id.pay_vip://vip用户续费
                if (info.getData().getUser().getType_class() == 5) {
                    payVIP = 0;
                } else {
                    payVIP = 1;
                }
                payPrice();
                break;
        }
    }

    // 获取vip以及超级vip的金额,给用户认证
    private void payPrice() {
        DesignerReq baseReq = new DesignerReq();
        baseReq.setCmd(Constant.DESIGNER_GETFEEPRICE);
        Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(baseReq));
        mSubscription = ApiImp.get().getFeePrice(requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PayPriceModel>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(PayPriceModel model) {
                        Log.e("model11", new Gson().toJson(model));
                        if (model != null) {
                            if (info != null) {
                                if (mPopPay == null) {
                                    mPopPay = new PopPay(getActivity(), model, info.getData().getUser().getType(), payVIP, tv_vip);
                                }
                                mPopPay.show();
                            }
                        }
                    }
                });
    }


    private boolean setPhone() {
        //判断是否是第三方登录是否绑定手机号；
        info = LoginUtil.getInfo(getContext());
        if (info != null) {
            LoginModle.DataBean data = info.getData();
            if (data != null) {
                if (data.getUser().getLoginType().equals("1")) {
                    return true;
                } else {
                    LoginModle.DataBean.UserBean user = data.getUser();
                    if (user != null) {
                        String userName = user.getUsername();
                        String userMobile = user.getMobile();
                        if (userName.equals(userMobile)) {
                            return false;
                        }
                        return true;
                    }
                }
            }
        }
        return false;
    }


    /**
     * 获取读取内存卡，和 拍照的权限 Android 6.0 以后
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //应用还未获取读取本地文件 的权限，询问是否允许
            ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, DesignApplySelectPhotoAdapter.PERMISSON_STORGE);
        } else {
            selectPhoto();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == DesignApplySelectPhotoAdapter.PERMISSON_STORGE) {
            if (grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                selectPhoto();
            } else {
                showToast("权限被禁止，无法选取图片");
            }
        }
    }

    /**
     * 选择图片
     */
    private void selectPhoto() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .isCamera(true)//列表是否显示拍照按钮
                .selectionMode(PictureConfig.SINGLE)
                .isEnableCrop(true)
                .withAspectRatio(1000, 1000)
                .cutOutQuality(80)
                .minimumCompressSize(400)
                .cropImageWideHigh(256, 256)
                .scaleEnabled(true)
                .rotateEnabled(false)
                .isCompress(true)
                .minimumCompressSize(400)
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .imageEngine(GlideEngine.createGlideEngine()) // Please refer to the Demo GlideEngine.java
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    /**
     * 剪切图片完成回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // onResult Callback
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    path = selectList.get(0).getCutPath();
                    upBase64();
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 将path转化成base64上传
     */
    private void upBase64() {
        str = Base64Helper.encodeBase64File(path);
        updateAvatar();
    }

    /**
     * 上传头像
     */
    private void updateAvatar() {
        BaseReq baseReq = new BaseReq();
        baseReq.setCmd(Constant.USER_AVATAR);
        BaseReq.ContentBean contentBean = new BaseReq.ContentBean();
        contentBean.setAvatar(str);
        baseReq.setContent(contentBean);
        Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(baseReq));
        RequestBody requestBodyl = RequestBody.create(MediaType.parse("application/session"), gson.toJson(LoginUtil.getInfo(mContext).getData().getSession()));
        showDialog("上传中");
        mSubscription = ApiImp.get().sendAvatar(requestBody, requestBodyl)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AvatarModel>() {
                    @Override
                    public void onCompleted() {
                        dissmissDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        dissmissDialog();
                        showToast("上传失败");
                    }

                    @Override
                    public void onNext(AvatarModel avatarModel) {
                        if (avatarModel.getStatus() == 0) {
                            T.showShort(mContext, "上传成功");
                            Picasso.with(mContext).load(avatarModel.getData().getUser().getAvatar().getUrl()).error(R.mipmap.ic_holder_header_big).into(imagePerson);
                            info.getData().getUser().getAvatar().setSmall(avatarModel.getData().getUser().getAvatar().getSmall());
                            info.getData().getUser().getAvatar().setThumb(avatarModel.getData().getUser().getAvatar().getThumb());
                            info.getData().getUser().getAvatar().setUrl(avatarModel.getData().getUser().getAvatar().getUrl());
                            LoginUtil.saveInfo(mContext, info);
                        }
                    }
                });
    }


    @Override
    public void setAction(String action) {
        if (action.equals("share")) {
            if (mPopShare == null) {
                mPopShare = new PopShare(mContext, mIwxapi, mIWeiboShareAPI, recycleView, Tag);
//                mPopShare.showER();
                if (info != null) {
                    mPopShare.setCodeText("邀请码:" + info.getData().getUser().getInvitecode());
                }
            }
            mPopShare.setmUrl(Constant.APP_DOWNLOAD_URL);
            mPopShare.setmSubhead("JAJAHOME下载链接");
            mPopShare.setText("");
            mPopShare.show();
        }
    }

    private void getUserTime() {
        ReqPage baseReq = new ReqPage();
        baseReq.setCmd(Constant.GETDESIGNERTIME);
        Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(baseReq));
        mSubscription = ApiImp.get().get_designer_time(requestBody, HttpUtil.getSession(mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<TimeModel>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(TimeModel model) {
                        timeDesc.setText(model.getData().getStart_time() + "至" + model.getData().getEnd_time());
                        Long noticeTime = Long.parseLong(TimeUtil.getTime(model.getData().getNotice_time()));
                        if (System.currentTimeMillis() > noticeTime) {
                            if (info != null) {
                                if (info.getData().getUser().getType_class() == 1) {//1为VIP会员
//                                    payBtn.setVisibility(View.GONE);
                                    pay_super_designer.setVisibility(View.GONE);
                                    pay_vip.setVisibility(View.VISIBLE);
                                } else if (info.getData().getUser().getType_class() == 5) {//直接续费布局不改
//                                    payBtn.setVisibility(View.VISIBLE);
                                    pay_vip.setVisibility(View.VISIBLE);
                                }
                                timeDesc.setVisibility(View.VISIBLE);
                            }
                        } else {
//                            payBtn.setVisibility(View.GONE);
                            timeDesc.setVisibility(View.VISIBLE);
                        }

                    }
                });
    }


    @Override
    public void onEventMainThread(EventMessage event) {
        super.onEventMainThread(event);
        if (event.action == Constant.LOGIN || event.action == Constant.diyTag) {
            refreshInfo();
        } else if (event.action == SettingAct.LOGIN_OUT_ACTION) {

        } else if (event.action == CHANGE_ACTION) {
            getUserInfo();
            payPrice();
        } else if (event.action == MPAY_METHOD) {
            String mPay = event.msg;
            int mPayWay = Integer.valueOf(mPay);
            if (mPayWay == 0) {
                //使用微信支付
                getWeichatPayInfo();
            } else if (mPayWay == 1) {
                getAlipayInfo();
            } else {
                showToast(getActivity().getResources().getString(R.string.select_way_pay));
            }
        } else if (event.action == WXPayEntryActivity.WEICAT_PAY_RESULT_ACTION) {
            dissmissDialog();
            //微信支付结果
            int code = Integer.valueOf(event.msg);
            if (code == BaseResp.ErrCode.ERR_USER_CANCEL) {
                showToast("已取消支付");
            } else if (code == BaseResp.ErrCode.ERR_OK) {
                showToast("支付成功");
                getUserInfo();
            }
        } else if (event.action == SUPER_DESIGNER_APLIAY) {
            getUserInfo();
        }
    }

    public void refreshInfo() {
        getUserInfo();
    }

    private void controlVIPPrice(final String id) {
        tvControlPrice.setVisibility(View.VISIBLE);
        tvControlPrice.setText(getShowVipPrice(id) ? R.string.hide_vip_price : R.string.show_vip_price);
        tvControlPrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean is = getShowVipPrice(id);
                is = !is;
                setShoVipPrice(id, is);
                tvControlPrice.setText(is ? R.string.hide_vip_price : R.string.show_vip_price);
            }
        });
    }

    private boolean getShowVipPrice(String id) {
        boolean isShowVip = (boolean) SPUtils.get(getActivity(), "SHOW_VIP_PRICE" + id, false);
        Log.e("isShowVip:", id + isShowVip + "");
        return isShowVip;
    }

    private void setShoVipPrice(String id, boolean isShow) {
        SPUtils.put(getActivity(), "SHOW_VIP_PRICE" + id, isShow);
    }

    /**
     * 获取微信支付预处理信息
     */
    private void getWeichatPayInfo() {
        ReqPage baseReq = new ReqPage();
        baseReq.setCmd(Constant.DESIGNERMPAY);
        ReqPage.ContentBean data = new ReqPage.ContentBean();
        data.setMoney(new SharedPreferencesUtils(getContext()).getMoney());
        baseReq.setContent(data);
        Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(baseReq));
        Log.e("baseReq", new Gson().toJson(baseReq));
        showDialog("获取微信支付信息");
        mSubscription = ApiImp.get().designer_wxpay(requestBody, HttpUtil.getSession(mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JWeichatPayModel>() {
                    @Override
                    public void onCompleted() {
                        dissmissDialog();
                        showLoading(false, "");
                    }

                    @Override
                    public void onError(Throwable e) {
                        dissmissDialog();
                        showLoading(false, "");
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(JWeichatPayModel model) {
                        if (model.getStatus() == HttpCode.SUCCESS) {
                            showDialog("进入微信支付");
                            mIwxapi.sendReq(WxPayApi.genPayReq(model));
                        }
                    }
                });
    }


    /**
     * 获取支付宝预处理
     */
    private void getAlipayInfo() {
        ReqPage baseReq = new ReqPage();
        baseReq.setCmd(Constant.DESIGNERALIPAY);
        ReqPage.ContentBean data = new ReqPage.ContentBean();
        data.setMoney(new SharedPreferencesUtils(getContext()).getMoney());
        baseReq.setContent(data);
        Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(baseReq));
        showDialog("获取支付信息");
        mSubscription = ApiImp.get().designer_alipay(requestBody, HttpUtil.getSession(mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AlipayModel>() {
                    @Override
                    public void onCompleted() {
                        dissmissDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        dissmissDialog();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(AlipayModel model) {
                        if (model.getStatus() == HttpCode.SUCCESS) {
                            startAlipay(model.getData().getOrder_string());
                        }
                    }
                });
    }


    private void startAlipay(final String alipayInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(alipayInfo, true);
                Log.i("msp", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 支付宝支付结果在此回调
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(mContext, "支付成功", Toast.LENGTH_SHORT).show();
                        //支付成功 通知 我的订单处刷新列表
                        EventBus.getDefault().post(new EventMessage(SUPER_DESIGNER_APLIAY, ""));

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(mContext, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * 获取用户消息
     */
    private void getDesignerAuditFlag() {
        ReqPage reqPage = new ReqPage();
        reqPage.setCmd(Constant.GET_DESIGNER_AUDITFLAG);
        Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(reqPage));
        mSubscription = ApiImp.get().getDesignerAuditFlag(requestBody, HttpUtil.getSession(mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AuditModel>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(AuditModel userMessageModel) {
                        if (userMessageModel.getStatus() == HttpCode.SUCCESS) {
                            if (userMessageModel.getAuditflag() == 1) {
                                payVIP = 0;
                                payPrice();
                            } else {
                                startActivity(DesignerApplyAct.class);
                            }
                        }
                    }
                });
    }


}
